package database;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class MySQLReceptKompDAO implements ReceptKompDAO {
	
	private Connector conn = null;
	private ResultSet rs = null;

	public MySQLReceptKompDAO() throws DALException {
		conn = new Connector();
	}
	
	public ReceptKompDTO getReceptKomp(int receptId, int raavareId)
			throws DALException {
		ReceptKompDTO rkDTO = null;
		String query = "SELECT * FROM receptkomp WHERE receptId = " + receptId
				+ " AND raavareId = " + raavareId + ";";
		rs = conn.doQuery(query);

		try {
			while (rs.next()) {

				rkDTO = new ReceptKompDTO(rs.getInt(1), rs.getInt(2),
						rs.getDouble(3), rs.getDouble(4));
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return rkDTO;

	}

	public List<ReceptKompDTO> getReceptKompList(int receptId)
			throws DALException {
		List<ReceptKompDTO> rkDTO = new ArrayList<ReceptKompDTO>();
		String query = "SELECT * FROM receptkomp WHERE receptId = " + receptId
				+ ";";
		rs = conn.doQuery(query);
		try {
			if (!rs.first()) {
				throw new DALException("Recept komponent med receptId"
						+ receptId + "findes ikke");

			} else {
				rkDTO.add(new ReceptKompDTO(rs.getInt(1), rs.getInt(2), 
						rs.getDouble(3), rs.getDouble(4)));
			}
			while (rs.next()) { 
			rkDTO.add(new ReceptKompDTO(rs.getInt(1), rs.getInt(2), 
					rs.getDouble(3), rs.getDouble(4)));
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return rkDTO;
	}

	public List<ReceptKompDTO> getReceptKompList() throws DALException {
		List<ReceptKompDTO> rkDTO = new ArrayList<ReceptKompDTO>();
		String query = "SELECT * FROM receptkomp";

		rs = conn.doQuery(query);
		try {
			while (rs.next()) {

			
			rkDTO.add(new ReceptKompDTO(rs.getInt(1), rs.getInt(2), rs
					.getDouble(3), rs.getDouble(4)));
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return rkDTO;

	}

	public void createReceptKomp(ReceptKompDTO receptkomponent)
			throws DALException {
		
		conn.doUpdate("INSERT INTO receptkomp (receptId, raavareId, nomNetto,tolerance) VALUES"
				+ "("
				+ receptkomponent.getReceptId()
				+ ", "
				+ receptkomponent.getRaavareId()
				+ ","
				+ receptkomponent.getNomNetto()
				+ ","
				+ receptkomponent.getTolerance() + ");");
	}

	public void updateReceptKomp(ReceptKompDTO receptkomponent)
			throws DALException {
		conn.doUpdate("UPDATE receptkomp SET receptId = "
				+ receptkomponent.getReceptId() + ", raavareId =  "
				+ receptkomponent.getRaavareId() + " , nomNetto = "
				+ receptkomponent.getNomNetto() + ", tolerance = "
				+ receptkomponent.getTolerance() + ", receptId = "
				+ receptkomponent.getReceptId() + "  WHERE receptId = "
				+ receptkomponent.getReceptId() + " AND raavareId = "
				+ receptkomponent.getRaavareId());

	}

}
